<template>
	<view class="login-page">
		<!-- <view class="logo">
			 <img src="/static/images/login/jz_logo.png" class="start-img">
			 <view class="app-name">管手机</view>
			 <view class="app-type">家长端</view>
		</view> -->
		<view class="logo">
			<img src="/static/images/login/logo.png" class="start-img">
			<view class="app-name">家长守护助手</view>
			<view class="app-small">SURGICAL MONITOR</view>
		</view>
		<view class="login-methon-one" v-if="loginType === 'phone'">
			<view class="login-form">
				<view class="input-cell">
					<uni-easyinput
					  v-model="phone"
					  prefixIcon="phone"
					  size="large"
					  type="number"
					  placeholder="请输入手机号"
					  clearable
					  :border="true"
					  extra-event-params
					  maxlength="11"
					  :inputBorder="true"
					  @change="onChange"
					  primaryColor="#69cf85"
					  borderColor="#69cf85"
					   class="base-login-input"
					>
					</uni-easyinput>
				</view>
				<view class="input-cell">
					<uni-easyinput
					  v-model="code"
					  size="large"
					  prefixIcon="locked"
					  type="number"
					  placeholder="请输入验证码"
					  clearable
					  :border="true"
					  extra-event-params
					  maxlength="6"
					  :inputBorder="true"
					  @change="onChangeCode"
					  suffixIcon="获取验证码"
					  primaryColor="#69cf85"
					  borderColor="#69cf85"
					  class="base-login-input"
					>
					</uni-easyinput>
					<view class="get-code-box">
						<view class="get-code" v-if="!state.isCounting && !state.canSendAgain" @click="getCode">获取验证码</view>  
						<view class="get-code" v-if="state.isCounting" disabled>{{ state.countdown }}s</view>  
						<view class="get-code" v-if="state.canSendAgain" @click="resetCountdown">重新发送</view>  
					</view>
				</view>
			</view> 
			<view class="register-tips">
				<checkbox-group @change="changeCheckbox"><checkbox :value="checked"  color="#69cf85" /></checkbox-group>登录注册即表示同意<view class="goto-link" @click="() => gotoPage('/pagesC/userAgreement/index')">《用户协议》</view>和<view class="goto-link" @click="() => gotoPage('/pagesC/policyPrivacy/index')">《隐私政策》</view>
			</view>
			<view class="login-register">
				<view class="login-register-btn" @click="login">登录</view>
				<view class="login-register-btn experience" @click="onExperience">无账号进入体验</view>
			</view>
			<view v-if="false" class="switch-quick-login" @click="switchLoginType('wx')"> <image src="/static/icon/weixin.png" class="weixin-icon"></image>手机号登录</view>
		
		</view>
		
		<view class="login-methon-two" v-if="loginType === 'wx'">
			 <button type="default" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber" class="wx-quick-login">手机号登录</button>
			<view class="register-tips">
				<checkbox-group @change="changeCheckbox"><checkbox :value="checked" color="#69cf85" /></checkbox-group>登录注册即表示同意<view class="goto-link" @click="() => gotoPage('/pagesC/userAgreement/index')">《用户协议》</view>和<view class="goto-link" @click="() => gotoPage('/pagesC/policyPrivacy/index')">《隐私政策》</view>
			</view>
			<view v-if="false"   class="swith-phone-login" @click="switchLoginType('phone')">手机号登录</view>
		</view>
		<view v-if="showPrivacy">
			<Privacy  @onClose="onCancel" @onAgree="onAgreePrivacy" from="login"/>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onShow, onLoad } from "@dcloudio/uni-app"
import {ref, onMounted, computed} from "vue"
import { loginServer } from "@/common/index"
import {ValidateType, ValidateFun} from "./types"
import { countdownHooks } from "@/hooks/index"
import { useLoginStore} from '@/stores/useLoginStore.js'
import { global, local } from "@/utils/index.ts"
import Privacy from '@/components/privacy/index.vue'
// import websocket from '@/utils/ws.js';
// import { WEBSOCKET } from "@/utils/constant.js"





const { state, startCountdown, stopCountdown, resetCountdown } = countdownHooks.useCountdown() 
const loginStore = useLoginStore();

const decryptPhoneNumber = async (res) => {
	const privacyVal = global.getPrivacyByLocal();
	if(checked.value === false){ // 验证不通过
		validateErrorMsg('checked')
		return;
	}
	if(privacyVal !== "1"){
		showPrivacy.value = true;
		return;
	}
	console.log('自动登录', res)
	const {detail} = res
	const {code: phoneCode, encryptedData, iv, errMsg} = detail
	 if(errMsg === 'getPhoneNumber:ok'){
		return uni.login({
			provider:"weixin",
			 async success(res) {
				if(res?.errMsg === "login:ok"){
					console.log("phoneCode", res)
					let optiosns : any = {
						loginCode: res.code, 
						phoneCode,
						"appDownChannel": "jzshzs_xcx_douyin",
						"mobileBrand": "weixin",
						"memberType": "1",
						"pkg": "com.jzzs.parent",
						"versionCode": "3.1.1",
					}
					if(SHARECODE.value){
						optiosns.sharecode = SHARECODE.value
					}
					const { status, data, message} =	await loginServer.loginByUserPhone(optiosns)
					if(status === "200"){
						uni.hideLoading();
						// todo  暂时未联调登录接口
						if(data && data?.token){
							loginStore.setUserInfo(data);
							global.saveUserInfoToLocal(data)
							global.saveTokenToLocal(data.token)
							// try{  一周家长守护不需要 websocket
							// 	websocket.connectWebSocket(`${WEBSOCKET}${data.memberId}`)
							// }catch(e){
							// 	console.log(e)
							// }
						}
						uni.switchTab({
							url:"/pages/tabbar/home/index"
						})
					}else {
						uni.hideLoading();
						uni.showToast({
							title: message || '登录失败',
							icon:"none"
						})
					}
				}
			},
			fail(res) {
				console.log('fail', res)
			}
		})
	 }else {
		 uni.showToast({
		 	title:"获取手机号失败",
			icon:'none'
		 })
	 }

}

type loginTypeProps = 'wx' | 'phone'
const loginType = ref<loginTypeProps>('phone')
const switchLoginType = (type: loginTypeProps) => {
	loginType.value = type
}



const showPrivacy = ref(global.getPrivacyByLocal() === "1" ? false : true); // 0: 不同意  1: 同意


const onCancel = () => {
	showPrivacy.value = false;
}

const onAgreePrivacy = () => {
	global.savePrivacyToLocal("1")
	showPrivacy.value = false;
};


// 获取openId
const getOpenId = async ({code}) => {
	try{
		const { status, data } = await loginServer.getDouYinOpenId({code});
		if(status === "200"){ // todo 400 等后端改了，这个去掉
			global.saveOpenIdToLocal(JSON.stringify(data));
			loginStore.setOpenId(data);
		}
	}catch(e){
		console.log(e)
		//TODO handle the exception
	}
}
// 获取provider
// const queryProvider = async () => {
// 	return uni.getProvider({
// 		service: 'oauth',
// 		success: function (res) {
// 			const miniappLit  = ['toutiao', 'kuaishou', 'weixin']; // 字节小程序， 快手小程序，微信小程序
// 			 if (res.provider?.some( (item: string) => miniappLit.includes(item))) { // 此时为头条小程序
// 				if(~res.provider.indexOf('toutiao')){
// 					uni.login({
// 						provider: 'toutiao', //使用微信登录
// 						success(res) {
// 							const {errMsg, code} = res;
// 							console.log("code", res)
// 							if(errMsg === "login:ok"){
// 								// getOpenId({code});
// 							}
// 						}
// 					})
// 				}
// 			}
// 		}
// 	)
// }

// 进入页面获取openId
const openId = async () => {
	console.log('是否会一直走这个方法')
	// queryProvider()
	uni.login({
		 provider: 'toutiao', //使用字节登录 todo 注意在快手小程序这里不能写toutiao，要写快手的，否则无法获取openid
		success(res) {
			const {errMsg, code} = res;
			if(errMsg === "login:ok"){
				getOpenId({code});
			}
		},
		fail(res) {
			console.log('登录失败', res)
		},
		complete(res) {
			console.log('登录', res)
		}
	})
}
const SHARECODE = ref(null);
onLoad(({shareCode}) => {
	console.log("登录页的sharecode", shareCode)
	SHARECODE.value = shareCode
})


onMounted(() => {
	// openId();
})

onShow(() =>{	
	console.log('登录页')
	openId();
	var pages = getCurrentPages();
    console.log("pages", pages);	
	if(global.getToken()){
		uni.switchTab({
			url:"/pages/tabbar/home/index"
		})
	}
})
 

 
const phone = ref("");
const code = ref("");
const checked = ref(false);
const changeCheckbox = (e) => {
	const value = e.detail?.value?.length > 0
	checked.value = value
}

const onChange = (phoneNumber:any) =>{
	phone.value = phoneNumber
}

const onChangeCode = (codeNumber:any) => {
	code.value = codeNumber
}

// 跳转到用户协议或者营私政策
const gotoPage = (pageUrl: string) => {
	uni.navigateTo({
		url: `${pageUrl}?from=login`,
	})
}

// 验证
const validate : ValidateFun= () => {
	let regExpPhone = new RegExp(/^1[3-9]\d{9}$/);
	let regExpCode = new RegExp(/^\d{6}$/);
	let res : ValidateType = {
		type: '', // '' | 'phone' | 'code' | 'checked'
		check: true // false | true
	};
	if(checked.value === false){
		res.type = "checked";
		res.check = false;
	}
	if(!regExpCode.test(code.value)){
		res.type = 'code';
		res.check = false;
	}
	if(!regExpPhone.test(phone.value)){
		res.type = 'phone';
		res.check = false;
	}
	return res;
}

// 验证不通过的提示
const validateErrorMsg = (type: ValidateType["type"] ) : void => {
	let msg = "";
	if(type === "checked"){
		msg = "请勾选阅读用户协议和隐私协议"
	}
	if(type === "code"){
		msg = "手机验证码不对"
	}
	if(type === "phone"){
		msg = "手机号不对"
	}
	uni.showToast({
		icon:"none",
		title: msg,
	})
	return;
}

// 获取验证码
const getCode = async () => {
	let regExpPhone = new RegExp(/^1[3-9]\d{9}$/);
	console.log("手机号-----》", phone, phone.value);
	if(!regExpPhone.test(phone.value)){
		uni.showToast({
			icon:"none",
			title: "手机号不对",
		})
		return;
	}
	try{		
		const {status} = await loginServer.parentAideSendVCode({appType: 2, phone: phone.value});
		if(status === '200'){
			console.log('到这里来吗')
			startCountdown();
		} else {
			uni.showToast({
				icon:"none",
				title: "获取验证码出错",
			})
		}		
	}catch(e){
		//TODO handle the exception
	}
}


const login = async () => {
	const {check, type} = validate();
	const privacyVal = global.getPrivacyByLocal();
	if(!check){ // 验证不通过
		validateErrorMsg(type)
		return;
	}
	console.log('privacyVal', privacyVal)
	if(privacyVal !== "1"){
		showPrivacy.value = true;
		return;
	}
	try{
		uni.showLoading({
			title: '登录中...',
		});
		const loginParams: any = {
			"appDownChannel": "jzshzs_xcx_douyin",
			"mobileBrand": "weixin",
			"code": code.value,
			"appType": "2",
			"memberType": "1",
			"pkg": "com.jzzs.parent",
			"versionCode": "3.1.1",
			"username": phone.value,
		}
		if(SHARECODE.value){
			loginParams.sharecode = SHARECODE.value
		}
		const res = await loginServer.login(loginParams)
		if(res.status === "200"){
			uni.hideLoading();
			// todo  暂时未联调登录接口
			if(res?.data && res.data?.token){
				loginStore.setUserInfo(res.data);
				global.saveUserInfoToLocal(res.data)
				global.saveTokenToLocal(res.data.token)
				// if(res?.data?.memberId){ 一周家长首页抖音版本，不需要websocket链接
				// 	try{
				// 		websocket.connectWebSocket(`${WEBSOCKET}${res.data.memberId}`)
				// 	}catch(e){
				// 		console.log(e)
				// 	}
				// }
			}
			uni.switchTab({
				url:"/pages/tabbar/home/index"
			})
		}else {
			uni.hideLoading();
			uni.showToast({
				title: res?.message || '登录失败',
				icon:"none"
			})
		}
	}catch(e){
		console.log(e)
	}

}

const onExperience = () => {
	uni.switchTab({
		url:"/pages/tabbar/home/index"
	})
}


</script>

<style lang="scss">
	.login-page{
		.logo{
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			.app-name{
				font-weight: bold;
				color: #000000;
				font-size: 36upx;
			}
			.app-small{
				// margin-top: 450upx;
				position: absolute;
				bottom: -30upx;
				font-size: 20upx;
				color: #9a9a9a;
				letter-spacing: 15upx;
			}
		}
		
		.login-form{
			margin-top: 120upx;
			width: 100%;
			.input-cell{
				position: relative;
				padding: 15upx 50upx;
				.van-cell{
					background-color: #eceff4;
					border-radius: 60upx;
				}
				.base-login-input{
					.uni-easyinput__content{
						border-radius: 40upx;
					}
					input{
						height: 80upx;
					}
				}
			}
			
			.get-code-box{
				position: absolute;
				top: 40upx;
				right: 100upx;
				z-index: 1000;
			}
			.get-code{
				color: $blue-theme;
				font-size: 28upx;
			}
		}
		.register-tips{
			margin-top: 40upx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 25upx;
			color: #010101;
			.goto-link{
				color: $blue-theme;
				margin: 0 5upx;
			}
		}
		.login-register{
			width: calc(100% - 100upx);
			margin: 0 auto;
			margin-top: 80upx;
			.van-button{;
				padding:0 50upx;
				width: 100%;
			}
		}
	}
</style>

<style scoped lang="scss">
	.login-page{
		position: relative;
		min-width: 100vw;
		min-height: 100vh;
		display: flex;
		align-items: center;
		flex-direction: column;
		background-color: #fff; /* 或者其他你希望的背景颜色 */
		.logo{
			position: relative;
			// top:100upx;
			top:0;
			width: 328px;
			min-height: 216px;
			background: url('/static/images/login/texture.png') center center no-repeat;
			.start-img{
				position: absolute;
				top: 0;
				right: 0;
				bottom: 0;
				left: 0;
				margin: auto;
				width: 250px;
				height: 250px;
				// object-fit: cover; /* 保持原始宽高比，填充容器 */
			}
			.app-name{
				position: absolute;
				bottom: -90upx;
				font-weight: 600;
				font-size: 40upx;
				color: #081A2A;
				text-align: center;
				font-style: normal;
				text-transform: none;
			}
			.app-type{
				position: absolute;
				bottom: 50upx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 600;
				font-size: 72upx;
				color: #081A2A;
				line-height: 84upx;
				text-align: center;
				font-style: normal;
				text-transform: none;
			}
		}
	}
	
	
	.login-methon-one{
		position: relative;
		height: calc(100vh - 228px);
		width: 100%;
		.switch-quick-login{
			position: absolute;
			left: 0;
			right: 0;
			bottom: 80upx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: 600;
			font-size: 28upx;
			color: #24DB5A;
			.weixin-icon{
				width: 40upx;
				height:40upx;
				margin-right: 32upx;
				text-align: center;
				font-style: normal;
				text-transform: none;
			}
		}
	}
	
	
	.login-methon-two{
		position: relative;
		height: calc(100vh - 328px);
		width: 100%;
		.wx-quick-login{
			width: 90%;
			height: 108upx;
			margin-top: 300upx;
			line-height: 108upx;
			background: #24DB5A;
			border-radius: 54upx;
			border: 1px solid #22DB58;
			color: #fff;
			font-size: 32upx;
			color: #FFFFFF;
			text-align: center;
			font-style: normal;
			text-transform: none;
		}
		.register-tips{
			margin-top: 40upx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 25upx;
			color: #010101;
			.goto-link{
				color: $blue-theme;
				margin: 0 5upx;
			}
		}
		.swith-phone-login{
			position: absolute;
			bottom:0upx;
			width: 100%;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 28upx;
			color: $themeColor;
			text-align: center;
			font-style: normal;
			text-transform: none;
		}
	}
	
	.login-register-btn{
		background-color: $themeColor;
		text-align: center;
		border: none;
		color: #fff;
		width: 100%;
		height: 108upx;
		line-height: 108upx;
		border-radius: 54upx;
		font-size: 32upx;
		color: #FFFFFF;
		text-align: center;
		font-style: normal;
		text-transform: none;
	}
	
	.experience{
		border: 1px solid $themeColor;
		margin-top: 40upx;
		background-color: #fff;
		color: #010101;
	}
</style>

